<template>
  <div class="app-container">
    <div class="top">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/static-site/static-site/' }">静态网站管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ siteName }} - 菜单管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="top">
      <el-input
        v-model="kwInput"
        placeholder="输入菜单名称进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加菜单')"
      >添加菜单
      </el-button>
      <el-button
        type="success"
        class="el-icon-menu create-nav-btn"
        :disabled="listLoading"
        @click="handleCreateCategoryNavigation"
      >一键创建目录页导航
      </el-button>
    </div>

    <el-table
      v-loading.body="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="left" label="菜单名称" prop="name" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="菜单类型" prop="menu_type" width="120">
        <template slot-scope="scope">
          <el-tag :type="getMenuTypeColor(scope.row.menu_type)">
            {{ getMenuTypeLabel(scope.row.menu_type) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="Logo" width="80">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.logo_url && scope.row.menu_type === 'main'"
            :src="scope.row.logo_url"
            :preview-src-list="[scope.row.logo_url]"
            fit="contain"
            style="width: 40px; height: 40px;"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="菜单项数量" width="120">
        <template slot-scope="scope">
          <el-badge :value="scope.row.menu_items_count || 0" type="primary">
            <el-button size="mini" @click="handleManageItems(scope.row)">管理菜单项</el-button>
          </el-badge>
        </template>
      </el-table-column>

      <el-table-column align="center" label="排序" prop="sort_order" width="80" />

      <el-table-column align="center" label="状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
            {{ scope.row.is_active ? '激活' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" prop="create_at" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.create_at }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="450">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handlePreview(scope.row)">预览</el-button>
          <el-button size="mini" type="info" @click="handleAction('edit', scope.row)">编辑</el-button>
          <el-button size="mini" type="warning" @click="openMenuBuilder(scope.row)">构建器</el-button>
          <el-button size="mini" type="success" @click="handleGenerateCode(scope.row)">生成代码</el-button>
          <el-button size="mini" type="success" @click="handleCreateCategoryNavigationForMenu(scope.row)">创建目录页导航</el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total>0"
      background
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 菜单编辑对话框 -->
    <el-dialog
      class="mt-dialog"
      :title="title"
      :width="width"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="100px">
        <el-form-item v-if="action !== 'delete'" label="菜单名称">
          <el-input v-model="temp.name" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="菜单类型">
          <el-select v-model="temp.menu_type" placeholder="请选择菜单类型">
            <el-option
              v-for="item in menuTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="action !== 'delete' && temp.menu_type === 'main'" label="Logo 图片">
          <el-input v-model="temp.logo_url" placeholder="请输入 Logo 图片地址（可选）" />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            主导航菜单可以配置 Logo 图片，将显示在品牌名称旁边
          </div>
          <div v-if="temp.logo_url" style="margin-top: 10px;">
            <el-image
              :src="temp.logo_url"
              fit="contain"
              style="max-height: 80px; max-width: 200px; border: 1px solid #ddd; padding: 5px;"
            >
              <div slot="error" class="image-slot" style="font-size: 12px; color: #999;">
                <i class="el-icon-picture-outline" /> 图片加载失败
              </div>
            </el-image>
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="排序">
          <el-input-number v-model="temp.sort_order" :min="0" :max="9999" placeholder="数字越小排序越前" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="状态">
          <el-switch v-model="temp.is_active" active-text="激活" inactive-text="停用" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete' && temp.code" label="生成的代码">
          <el-input
            v-model="temp.code"
            type="textarea"
            :rows="10"
            readonly
            style="font-family: monospace; font-size: 12px;"
          />
          <div style="margin-top: 10px;">
            <el-switch v-model="temp.enable" active-text="启用代码" inactive-text="停用代码" />
            <span style="margin-left: 10px; color: #909399; font-size: 12px;">
              启用后，页面将使用此代码渲染菜单
            </span>
          </div>
        </el-form-item>

        <div v-if="action === 'delete'" style="text-align: center; font-size: 16px;">
          确认要删除菜单 <strong>{{ temp.name }}</strong> 吗？
          <br><br>
          <el-alert title="警告：删除菜单将同时删除所有菜单项！" type="warning" show-icon />
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 菜单项管理对话框 -->
    <el-dialog
      title="菜单项管理"
      :visible.sync="itemDialogVisible"
      width="90%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <div class="menu-item-container">
        <div class="menu-item-header">
          <span class="menu-title">{{ currentMenu.name }} - 菜单项</span>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleItemAction('create')"
          >
            添加菜单项
          </el-button>
        </div>

        <el-table
          v-loading="itemLoading"
          :data="menuItems"
          border
          row-key="id"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          style="width: 100%"
        >
          <el-table-column label="菜单标题" prop="title" width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.title }}</span>
            </template>
          </el-table-column>

          <el-table-column label="链接类型" prop="link_type" width="120">
            <template slot-scope="scope">
              <el-tag :type="getLinkTypeColor(scope.row.link_type)">
                {{ getLinkTypeLabel(scope.row.link_type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="链接地址" prop="url" min-width="200">
            <template slot-scope="scope">
              <a :href="scope.row.url" target="_blank" class="link-preview">
                {{ scope.row.url }}
              </a>
            </template>
          </el-table-column>

          <el-table-column label="图标" prop="icon_class" width="80">
            <template slot-scope="scope">
              <i v-if="scope.row.icon_class" :class="scope.row.icon_class" />
              <span v-else>-</span>
            </template>
          </el-table-column>

          <el-table-column label="排序" prop="sort_order" width="80" />

          <el-table-column label="状态" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
                {{ scope.row.is_active ? '激活' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleItemAction('edit', scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleItemAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="itemDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 菜单项编辑对话框 -->
    <el-dialog
      :title="itemAction === 'create' ? '添加菜单项' : (itemAction === 'edit' ? '编辑菜单项' : '删除菜单项')"
      :visible.sync="itemEditDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="tempItem" label-position="left" label-width="100px">
        <el-form-item v-if="itemAction !== 'delete'" label="菜单标题">
          <el-input v-model="tempItem.title" placeholder="请输入菜单标题" />
        </el-form-item>

        <el-form-item v-if="itemAction !== 'delete'" label="父级菜单">
          <el-select v-model="tempItem.parent" placeholder="请选择父级菜单（可选）" clearable>
            <el-option
              v-for="item in parentMenuItems"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="itemAction !== 'delete'" label="链接类型">
          <el-select v-model="tempItem.link_type" placeholder="请选择链接类型" @change="handleLinkTypeChange">
            <el-option
              v-for="item in linkTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="itemAction !== 'delete' && tempItem.link_type === 'page'" label="目标页面">
          <el-select v-model="tempItem.target_page" placeholder="请选择目标页面" filterable>
            <el-option
              v-for="item in pageOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="itemAction !== 'delete' && tempItem.link_type === 'category'" label="目标分类">
          <el-select v-model="tempItem.target_category" placeholder="请选择目标分类" filterable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="itemAction !== 'delete' && (tempItem.link_type === 'external' || tempItem.link_type === 'custom')" label="自定义链接">
          <el-input v-model="tempItem.custom_url" placeholder="请输入完整的链接地址" />
        </el-form-item>

        <el-form-item v-if="itemAction !== 'delete'" label="图标CSS类">
          <el-input v-model="tempItem.icon_class" placeholder="请输入图标CSS类名（可选）" />
        </el-form-item>

        <el-form-item v-if="itemAction !== 'delete'" label="排序">
          <el-input-number v-model="tempItem.sort_order" :min="0" :max="9999" placeholder="数字越小排序越前" />
        </el-form-item>

        <el-form-item v-if="itemAction !== 'delete'" label="新窗口打开">
          <el-switch v-model="tempItem.open_in_new_tab" active-text="是" inactive-text="否" />
        </el-form-item>

        <el-form-item v-if="itemAction !== 'delete'" label="状态">
          <el-switch v-model="tempItem.is_active" active-text="激活" inactive-text="停用" />
        </el-form-item>

        <div v-if="itemAction === 'delete'" style="text-align: center; font-size: 16px;">
          确认要删除菜单项 <strong>{{ tempItem.title }}</strong> 吗？
          <br><br>
          <el-alert title="警告：删除菜单项将同时删除所有子菜单项！" type="warning" show-icon />
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="itemEditDialogVisible = false">取 消</el-button>
        <el-button :type="itemAction !== 'delete'?'primary':'danger'" @click="confirmItem">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 菜单预览对话框 -->
    <el-dialog
      title="菜单预览"
      :visible.sync="previewVisible"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <div class="menu-preview-container">
        <div class="preview-header">
          <el-tag type="info">{{ previewMenu.name }}</el-tag>
          <span style="margin-left: 10px; color: #666;">{{ getMenuTypeLabel(previewMenu.menu_type) }}</span>
          <el-image
            v-if="previewMenu.logo_url && previewMenu.menu_type === 'main'"
            :src="previewMenu.logo_url"
            fit="contain"
            style="max-height: 40px; float: right;"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
        </div>
        <div class="menu-preview-content">
          <div v-if="previewMenuTree.length === 0" class="empty-menu">
            该菜单暂无菜单项
          </div>
          <div v-else class="menu-tree">
            <div
              v-for="item in previewMenuTree"
              :key="item.id"
              class="menu-item-preview"
            >
              <div class="menu-item-info">
                <i v-if="item.icon_class" :class="item.icon_class" />
                <a :href="item.url" target="_blank" class="menu-item-link">{{ item.title }}</a>
                <el-tag v-if="item.open_in_new_tab" size="mini" type="info">新窗口</el-tag>
              </div>
              <div v-if="item.children && item.children.length > 0" class="submenu-items">
                <div
                  v-for="child in item.children"
                  :key="child.id"
                  class="submenu-item-preview"
                >
                  <i v-if="child.icon_class" :class="child.icon_class" />
                  <a :href="child.url" target="_blank" class="submenu-item-link">{{ child.title }}</a>
                  <el-tag v-if="child.open_in_new_tab" size="mini" type="info">新窗口</el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 代码预览对话框 -->
    <el-dialog
      title="菜单代码"
      :visible.sync="codeDialogVisible"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <div class="code-preview-container">
        <div class="code-header">
          <span>{{ codeMenu.name }} - {{ getMenuTypeLabel(codeMenu.menu_type) }}</span>
          <span class="code-style-tag">代码风格: {{ currentCodeStyle }}</span>
          <el-button
            type="primary"
            size="mini"
            style="float: right;"
            @click="handleCopyCode"
          >
            复制代码
          </el-button>
        </div>
        <div v-if="codeMenu.logo_url && codeMenu.menu_type === 'main'" class="code-logo-info">
          <el-alert
            :title="`Logo 图片: ${codeMenu.logo_url}`"
            type="success"
            :closable="false"
            show-icon
          />
        </div>
        <div v-if="!codeMenu.logo_url && codeMenu.menu_type === 'main'" class="code-logo-info">
          <el-alert
            title="提示：您可以设置 Logo 图片地址来显示品牌 Logo"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
        <div class="menu-structure-info">
          <el-alert
            :title="`菜单结构：共 ${getMenuItemCount()} 个菜单项`"
            :description="`菜单项包括：${getMenuItemTitles()}`"
            type="info"
            :closable="false"
          />
        </div>
        <div class="code-content">
          <el-input
            v-model="menuCode"
            type="textarea"
            :rows="20"
            readonly
            class="code-textarea"
          />
        </div>
        <div class="code-info">
          <el-alert
            title="提示"
            type="info"
            :closable="false"
            show-icon
          >
            此代码基于网站设置的 {{ currentCodeStyle }} 风格生成。您可以直接复制使用，或根据需要进行调整。
          </el-alert>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="warning" @click="handleRegenerateCode">重新生成</el-button>
        <el-button type="success" @click="handlePreviewMenuCode">预览菜单</el-button>
        <el-button @click="codeDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getStaticSiteMenuList,
  createStaticSiteMenu,
  updateStaticSiteMenu,
  deleteStaticSiteMenu,
  getStaticSiteMenuItemList,
  createStaticSiteMenuItem,
  updateStaticSiteMenuItem,
  deleteStaticSiteMenuItem,
  getStaticSiteMenuTree,
  getStaticSiteMenuOptions,
  createCategoryNavigation,
  generateMenuCode
} from '@/api/spider/static_site'

export default {
  name: 'StaticSiteMenu',
  data() {
    return {
      data: [],
      listLoading: true,
      kwInput: '',
      listQuery: {
        page: 1,
        pageSize: 20
      },
      total: 0,
      siteId: null,
      siteName: '',

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        name: '',
        menu_type: 'main',
        sort_order: 0,
        is_active: true,
        code: '',
        enable: true,
        logo_url: ''
      },
      width: '50%',

      menuTypeOptions: [
        { value: 'main', label: '主导航' },
        { value: 'footer', label: '页脚导航' },
        { value: 'sidebar', label: '侧边导航' },
        { value: 'breadcrumb', label: '面包屑导航' }
      ],

      // 菜单项管理
      itemDialogVisible: false,
      itemEditDialogVisible: false,
      itemLoading: false,
      itemAction: null,
      currentMenu: {},
      menuItems: [],
      parentMenuItems: [],
      tempItem: {
        title: '',
        link_type: 'page',
        target_page: null,
        target_category: null,
        custom_url: '',
        icon_class: '',
        sort_order: 0,
        open_in_new_tab: false,
        is_active: true,
        parent: null,
        menu: null
      },

      linkTypeOptions: [
        { value: 'page', label: '内部页面' },
        { value: 'category', label: '分类页面' },
        { value: 'external', label: '外部链接' },
        { value: 'custom', label: '自定义链接' }
      ],

      // 选项数据
      pageOptions: [],
      categoryOptions: [],

      // 菜单预览
      previewVisible: false,
      previewMenu: {},
      previewMenuTree: [],

      // 代码预览
      codeDialogVisible: false,
      codeMenu: {},
      menuCode: '',
      currentCodeStyle: ''
    }
  },
  created() {
    this.siteId = this.$route.query.site_id
    this.siteName = this.$route.query.site_name || '未知网站'
    if (!this.siteId) {
      this.$message.error('缺少网站ID参数')
      this.$router.push('/static-site/static-site/')
      return
    }
    this.getList()
    this.getMenuOptions()
  },
  methods: {
    resetTemp() {
      this.temp = {
        name: '',
        menu_type: 'main',
        sort_order: 0,
        is_active: true,
        site_id: this.siteId,
        code: '',
        enable: true,
        logo_url: ''
      }
    },
    resetTempItem() {
      this.tempItem = {
        title: '',
        link_type: 'page',
        target_page: null,
        target_category: null,
        custom_url: '',
        icon_class: '',
        sort_order: 0,
        open_in_new_tab: false,
        is_active: true,
        parent: null,
        menu: this.currentMenu && this.currentMenu.id ? this.currentMenu.id : null
      }
    },
    getList() {
      this.listLoading = true
      const params = {
        page: this.listQuery.page,
        pageSize: this.listQuery.pageSize,
        site_id: this.siteId
      }
      if (this.kwInput) {
        params.kw = this.kwInput
      }

      getStaticSiteMenuList(new URLSearchParams(params).toString())
        .then(response => {
          if (response.success) {
            this.data = response.data.data
            this.total = response.data.total
          } else {
            this.$message.error('获取数据失败：' + response.msg)
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.$message.error('获取数据失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          this.listLoading = false
        })
    },
    getMenuOptions() {
      getStaticSiteMenuOptions(this.siteId)
        .then(response => {
          if (response.success) {
            this.pageOptions = response.data.pages
            this.categoryOptions = response.data.categories
          }
        }).catch(err => {
          console.log('获取菜单选项失败:', err)
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '添加菜单'
          this.resetTemp()
          this.dialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = '编辑菜单'
          this.temp = Object.assign({}, row)
          this.temp.site_id = this.siteId
          // 确保有默认值
          if (this.temp.enable === undefined) {
            this.temp.enable = true
          }
          if (!this.temp.code) {
            this.temp.code = ''
          }
          if (!this.temp.logo_url) {
            this.temp.logo_url = ''
          }
          this.dialogVisible = true
          break
        case 'delete':
          this.width = '40%'
          this.title = '删除确认'
          this.temp = Object.assign({}, row)
          this.dialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          createStaticSiteMenu(_data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('添加成功')
            } else {
              this.$message.error('添加失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('添加失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'edit':
          updateStaticSiteMenu(_data.id, _data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('更新成功')
            } else {
              this.$message.error('更新失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('更新失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'delete':
          deleteStaticSiteMenu(_data.id).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('删除成功')
            } else {
              this.$message.error('删除失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('删除失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    getMenuTypeLabel(type) {
      const option = this.menuTypeOptions.find(item => item.value === type)
      return option ? option.label : type
    },
    getMenuTypeColor(type) {
      const colors = {
        'main': 'primary',
        'footer': 'success',
        'sidebar': 'info',
        'breadcrumb': 'warning'
      }
      return colors[type] || 'default'
    },
    getLinkTypeLabel(type) {
      const option = this.linkTypeOptions.find(item => item.value === type)
      return option ? option.label : type
    },
    getLinkTypeColor(type) {
      const colors = {
        'page': 'primary',
        'category': 'success',
        'external': 'warning',
        'custom': 'info'
      }
      return colors[type] || 'default'
    },
    // 菜单项管理
    handleManageItems(menu) {
      this.currentMenu = menu
      this.itemDialogVisible = true
      this.getMenuItems()
    },
    getMenuItems() {
      this.itemLoading = true
      const params = {
        menu_id: this.currentMenu.id,
        pagesize: 1000
      }

      getStaticSiteMenuItemList(new URLSearchParams(params).toString())
        .then(response => {
          if (response.success) {
            this.menuItems = this.buildMenuItemTree(response.data.data)
            this.parentMenuItems = response.data.data.filter(item => !item.parent)
          } else {
            this.$message.error('获取菜单项失败：' + response.msg)
          }
          this.itemLoading = false
        }).catch(err => {
          console.log(err)
          this.$message.error('获取菜单项失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          this.itemLoading = false
        })
    },
    buildMenuItemTree(items) {
      const tree = []
      const map = {}

      // 创建映射
      items.forEach(item => {
        map[item.id] = { ...item, children: [] }
      })

      // 构建树结构
      items.forEach(item => {
        if (item.parent) {
          if (map[item.parent]) {
            map[item.parent].children.push(map[item.id])
          }
        } else {
          tree.push(map[item.id])
        }
      })

      return tree
    },
    handleItemAction(action, row) {
      this.itemAction = action
      switch (action) {
        case 'create':
          this.resetTempItem()
          this.itemEditDialogVisible = true
          break
        case 'edit':
          this.tempItem = Object.assign({}, row)
          this.tempItem.menu = this.currentMenu && this.currentMenu.id ? this.currentMenu.id : row.menu
          this.itemEditDialogVisible = true
          break
        case 'delete':
          this.tempItem = Object.assign({}, row)
          this.itemEditDialogVisible = true
          break
      }
    },
    confirmItem() {
      const _data = this.tempItem
      switch (this.itemAction) {
        case 'create':
          createStaticSiteMenuItem(_data).then(response => {
            if (response.success) {
              this.itemEditDialogVisible = false
              this.getMenuItems()
              this.notify('添加成功')
            } else {
              this.$message.error('添加失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('添加失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'edit':
          updateStaticSiteMenuItem(_data.id, _data).then(response => {
            if (response.success) {
              this.itemEditDialogVisible = false
              this.getMenuItems()
              this.notify('更新成功')
            } else {
              this.$message.error('更新失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('更新失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'delete':
          deleteStaticSiteMenuItem(_data.id).then(response => {
            if (response.success) {
              this.itemEditDialogVisible = false
              this.getMenuItems()
              this.notify('删除成功')
            } else {
              this.$message.error('删除失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('删除失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
      }
    },
    handleLinkTypeChange() {
      // 清空相关字段
      this.tempItem.target_page = null
      this.tempItem.target_category = null
      this.tempItem.custom_url = ''
    },
    // 菜单预览
    handlePreview(menu) {
      this.previewMenu = menu
      this.previewVisible = true
      this.getMenuTree()
    },
    getMenuTree() {
      getStaticSiteMenuTree(this.previewMenu.id)
        .then(response => {
          if (response.success) {
            this.previewMenuTree = response.data
          } else {
            this.$message.error('获取菜单树失败：' + response.msg)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error('获取菜单树失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
        })
    },
    // 一键创建目录页导航（全局按钮）
    handleCreateCategoryNavigation() {
      if (this.data.length === 0) {
        this.$message.warning('请先创建菜单')
        return
      }

      // 如果只有一个菜单，直接使用
      if (this.data.length === 1) {
        this.createCategoryNavigationForMenu(this.data[0])
        return
      }

      // 多个菜单时让用户选择
      this.$prompt('请选择要创建目录页导航的菜单', '选择菜单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'select',
        inputOptions: this.data.reduce((options, menu) => {
          options[menu.id] = menu.name
          return options
        }, {})
      }).then(({ value }) => {
        const selectedMenu = this.data.find(menu => menu.id === parseInt(value))
        if (selectedMenu) {
          this.createCategoryNavigationForMenu(selectedMenu)
        }
      }).catch(() => {
        // 用户取消
      })
    },
    // 为指定菜单创建目录页导航
    handleCreateCategoryNavigationForMenu(menu) {
      this.createCategoryNavigationForMenu(menu)
    },
    // 执行创建目录页导航
    createCategoryNavigationForMenu(menu) {
      this.$confirm('确定要为菜单 "' + menu.name + '" 创建目录页导航吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        createCategoryNavigation(menu.id).then(response => {
          if (response.success) {
            this.$message.success(response.msg)
            this.getList() // 刷新列表
          } else {
            this.$message.error('创建失败：' + response.msg)
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.$message.error('创建失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          this.listLoading = false
        })
      }).catch(() => {
        // 用户取消
      })
    },
    // 打开菜单构建器
    openMenuBuilder(menu) {
      this.$router.push({
        path: '/static-site/menu-builder/',
        query: {
          site_id: this.siteId,
          site_name: this.siteName,
          menu_id: menu.id,
          menu_name: menu.name
        }
      })
    },
    // 生成菜单代码
    handleGenerateCode(menu) {
      this.codeMenu = menu
      this.listLoading = true

      generateMenuCode(menu.id).then(response => {
        if (response.success) {
          this.menuCode = response.data.code
          this.currentCodeStyle = response.data.code_style
          this.codeDialogVisible = true
          this.$message.success('代码生成成功')
        } else {
          this.$message.error('生成代码失败：' + response.msg)
        }
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.$message.error('生成代码失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
        this.listLoading = false
      })
    },
    // 重新生成代码
    handleRegenerateCode() {
      this.handleGenerateCode(this.codeMenu)
    },
    // 预览菜单代码
    handlePreviewMenuCode() {
      this.codeMenu = this.codeMenu // 确保 codeMenu 有值
      if (!this.codeMenu.id) {
        this.$message.warning('请先生成代码')
        return
      }
      this.codeDialogVisible = true
      this.getMenuTree() // 预览时也需要菜单树
      if (!this.menuCode) {
        this.$message.warning('请先生成代码')
        return
      }

      // 生成完整的预览HTML
      const previewHtml = this.generatePreviewHtml()

      // 在新窗口中打开预览
      const previewWindow = window.open('', '_blank', 'width=1200,height=800,scrollbars=yes,resizable=yes')
      previewWindow.document.open()
      previewWindow.document.write(previewHtml)
      previewWindow.document.close()
    },

    // 生成预览HTML页面
    generatePreviewHtml() {
      const codeStyle = this.currentCodeStyle || 'bootstrap5'
      const menuCode = this.menuCode || ''
      const siteName = this.siteName || '网站预览'

      // 根据代码风格添加相应的CSS和JS库
      let cssLinks = ''
      let jsLinks = ''

      if (codeStyle === 'bootstrap5') {
        cssLinks = '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">'
        jsLinks = '<' + 'script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"><' + '/script>'
      } else if (codeStyle === 'bootstrap4') {
        cssLinks = '<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">'
        jsLinks = '<' + 'script src="https://code.jquery.com/jquery-3.6.0.min.js"><' + '/script><' + 'script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"><' + '/script>'
      } else if (codeStyle === 'tailwind') {
        cssLinks = '<' + 'script src="https://cdn.tailwindcss.com"><' + '/script>'
        jsLinks = ''
      } else {
        cssLinks = '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">'
        jsLinks = '<' + 'script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"><' + '/script>'
      }

      const html = '<!DOCTYPE html>' +
        '<html lang="zh-CN">' +
        '<head>' +
        '<meta charset="UTF-8">' +
        '<meta name="viewport" content="width=device-width, initial-scale=1.0">' +
        '<title>' + siteName + ' - 菜单预览</title>' +
        cssLinks +
        '<style>' +
        'body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background-color: #f8f9fa; }' +
        '.demo-content { padding: 40px 20px; background: #fff; margin: 20px auto; max-width: 1200px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }' +
        '.demo-hero { text-align: center; padding: 60px 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; margin-bottom: 20px; border-radius: 8px; }' +
        '.demo-hero h1 { font-size: 2.5rem; margin-bottom: 1rem; font-weight: bold; }' +
        '.demo-hero p { font-size: 1.2rem; opacity: 0.9; }' +
        '.demo-section { margin: 40px 0; }' +
        '.demo-section h2 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; margin-bottom: 20px; }' +
        '.demo-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-top: 30px; }' +
        '.demo-card { padding: 20px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #007bff; }' +
        '</style>' +
        '</head>' +
        '<body>' +
        // 菜单代码直接放在顶部
        menuCode +
        // 简化的页面内容
        '<div class="demo-content">' +
        '<div class="demo-hero">' +
        '<h1>欢迎来到我们的网站</h1>' +
        '<p>这是一个菜单预览示例页面，展示导航菜单的实际效果</p>' +
        '</div>' +
        '<div class="demo-section">' +
        '<h2>关于我们</h2>' +
        '<p>我们是一家专业的公司，致力于为客户提供优质的产品和服务。通过上方的导航菜单，您可以浏览我们网站的各个页面。</p>' +
        '</div>' +
        '<div class="demo-cards">' +
        '<div class="demo-card">' +
        '<h3>产品展示</h3>' +
        '<p>浏览我们的产品目录，了解我们提供的各种解决方案。</p>' +
        '</div>' +
        '<div class="demo-card">' +
        '<h3>服务支持</h3>' +
        '<p>我们提供专业的技术支持和售后服务，确保您的满意。</p>' +
        '</div>' +
        '<div class="demo-card">' +
        '<h3>联系我们</h3>' +
        '<p>如有任何问题，请随时通过导航菜单中的联系方式与我们联系。</p>' +
        '</div>' +
        '</div>' +
        '</div>' +
        jsLinks +
        '</body>' +
        '</html>'

      return html
    },
    // 复制代码
    handleCopyCode() {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(this.menuCode).then(() => {
          this.$message.success('代码已复制到剪贴板')
        }).catch(() => {
          this.fallbackCopyCode()
        })
      } else {
        this.fallbackCopyCode()
      }
    },
    // 降级复制方法
    fallbackCopyCode() {
      const textarea = document.createElement('textarea')
      textarea.value = this.menuCode
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      textarea.select()
      try {
        document.execCommand('copy')
        this.$message.success('代码已复制到剪贴板')
      } catch (err) {
        this.$message.error('复制失败，请手动复制')
      }
      document.body.removeChild(textarea)
    },
    getMenuItemCount() {
      if (!this.codeMenu || !this.codeMenu.id) {
        return 0
      }
      // 从菜单的 items 获取菜单项数量
      const items = this.menuItems.filter(item => item.menu_id === this.codeMenu.id)
      return items.length
    },
    getMenuItemTitles() {
      if (!this.codeMenu || !this.codeMenu.id) {
        return '无菜单项'
      }
      // 从菜单的 items 获取菜单项标题
      const items = this.menuItems.filter(item => item.menu_id === this.codeMenu.id)
      if (items.length === 0) {
        return '无菜单项'
      }
      return items.slice(0, 5).map(item => item.title).join('，') + (items.length > 5 ? '...' : '')
    }
  }
}
</script>

<style scoped>
.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 400px);
}

.add-btn {
  float: right;
  margin-right: 10px;
  width: 120px
}

.create-nav-btn {
  float: right;
  margin-right: 20px;
  width: 170px
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-dialog {
  margin: 88px auto !important;
}

.menu-item-container {
  height: 100%;
}

.menu-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.menu-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.link-preview {
  color: #409EFF;
  text-decoration: none;
  word-break: break-all;
}

.link-preview:hover {
  text-decoration: underline;
}

.menu-preview-container {
  height: 100%;
}

.preview-header {
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.menu-preview-content {
  min-height: 400px;
}

.empty-menu {
  text-align: center;
  color: #999;
  padding: 50px;
  font-size: 16px;
}

.menu-tree {
  padding: 20px;
}

.menu-item-preview {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.menu-item-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.menu-item-link {
  color: #409EFF;
  text-decoration: none;
  font-size: 16px;
  font-weight: bold;
}

.menu-item-link:hover {
  text-decoration: underline;
}

.submenu-items {
  margin-left: 20px;
  padding-left: 20px;
  border-left: 2px solid #e4e7ed;
}

.submenu-item-preview {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

.submenu-item-link {
  color: #666;
  text-decoration: none;
}

.submenu-item-link:hover {
  color: #409EFF;
  text-decoration: underline;
}

/* 代码预览样式 */
.code-preview-container {
  height: 100%;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.code-style-tag {
  background: #f0f2f5;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}

.code-logo-info {
  margin-bottom: 15px;
}

.menu-structure-info {
  margin-bottom: 15px;
}

.code-content {
  margin-bottom: 15px;
}

.code-textarea >>> .el-textarea__inner {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
  background: #f5f7fa;
  color: #303133;
}

.code-info {
  margin-bottom: 10px;
}
</style>
